package com.giscloud.token.utils;


import com.giscloud.commons.exception.TokenException;
import com.giscloud.commons.utils.JacksonUtil;
import com.giscloud.commons.utils.StringUtils;
import com.giscloud.redis.utils.RedisUtils;
import com.giscloud.token.cache.LocalCacheManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Classname TokenUserUtil
 * @Description 获取用户信息
 * @Date 2020/6/9 15:23
 * @Created by gis
 */
@Component
@Log4j2
public class TokenUserUtil {
    public final static String ACCESS_TOKEN = "giscloud-token";
    @Value("${spring.cache.type}")
    private String cacheType;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LocalCacheManager localCacheManager;

    public  HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public  String  getAccessToken(){
        String accessToken = getRequest().getHeader(ACCESS_TOKEN);
        if(StringUtils.isBlank(accessToken)){
            accessToken = getRequest().getParameter(ACCESS_TOKEN);
        }
        return accessToken;
    }
    /**
     * 获取登录用户信息
     *
     * @return
     */
    public  Token getToken(){
        String accessToken = getAccessToken();
        if(StringUtils.isEmpty(accessToken)){
            throw  new TokenException("无token请求头信息");
        }
        String userJson = "";
        if("redis".equals(cacheType)){
            if(ObjectUtils.isEmpty(redisUtils.get(RedisConstant.REDIS_USER_TOKEN + accessToken))){
                throw  new TokenException("token信息为空，请重新登录");
            }
            // 从Redis中获取用户信息
            userJson = (String) redisUtils.get(RedisConstant.REDIS_USER_TOKEN + getAccessToken());
        }else{
            if(ObjectUtils.isEmpty(localCacheManager.get(RedisConstant.REDIS_USER_TOKEN + accessToken))){
                throw  new TokenException("token信息为空，请重新登录");
            }
            // 从缓存中获取用户信息
            userJson = localCacheManager.get(RedisConstant.REDIS_USER_TOKEN + getAccessToken());
        }
        return JacksonUtil.json2Bean(userJson, Token.class);
    }

    /**
     * 获取当前登录用户id
     * @return
     */
    public  Long getUserId(){
        try {
            Token token = getToken();
            return token.getStaffId();
        } catch (Exception e) {
            log.error("token信息获取异常",e);
            return 1L;
        }
    }

    /**
     * 获取当前登录用户id
     * @return
     */
    public  String getStaffName(){
        try {
            Token token = getToken();
            return token.getStaffName();
        } catch (Exception e) {
            log.error("token信息获取异常",e);
            return "";
        }
    }

    /**
     * 获取登录用户所属机构id（单个）
     * @return
     */
    public  Long getOrgId(){
        try {
            Token token = getToken();
            Map orgMap = token.getOrgMap();
            return Long.valueOf(String.valueOf(((Map)orgMap.get(orgMap.keySet().toArray()[0])).get("orgId")));
        } catch (Exception e) {
            log.error("token信息获取异常",e);
            return 2L;
        }

    }

    /**
     * 获取登录用户所属机构编码（单个）
     * @return
     */
    public  String getOrgCode(){
        try {
            Token token = getToken();
            Map orgMap = token.getOrgMap();
            return String.valueOf(((Map)orgMap.get(orgMap.keySet().toArray()[0])).get("orgCode"));
        } catch (Exception e) {
            log.error("token信息获取异常",e);
            return "";
        }

    }

    /**
     * 获取角色
     * @return
     */
    public  List<String> getRolesId(){
        try {
            Token token = getToken();
            return token.getRolesId();
        } catch (Exception e) {
            log.error("token信息获取异常",e);
            return new ArrayList<>();
        }
    }
}
